// ============ 全局变量 ============
const url = "/api/rest/dept";
let gridInstance = null;
let deptData = null;

// ============ 让 fetch 自动带 Cookie ============
const originalFetch = window.fetch;
window.fetch = function (...args) {
  const [url, config = {}] = args;
  config.credentials = 'include';
  return originalFetch(url, config);
};

// ============ 表格配置 ============
const gridOptions = {
  columns: [
    { name: '编号', id: 'id', width: '8%' }, 
    { name: '父部门编号', id: 'parentId', width: '12%' },
    { name: '名称', id: 'name', sort: true },
    { name: '类型', id: 'type', sort: true },
    { name: '负责人', id: 'principal', sort: true },
    { name: '电话', id: 'phone', sort: true },
    { name: '备注', id: 'remark', sort: true },
    {
      name: '操作',
      id: 'actions',
      width: '20%',
      formatter: (_, row) => gridjs.html(`
        <button onclick="openEditModal('${row.cells[0].data}')" class="btn btn-sm btn-outline-primary m-1"><i class="fas fa-edit"></i> 编辑</button>
        <button onclick="toggleDept('${row.cells[0].data}')" class="btn btn-sm btn-outline-warning m-1"><i class="fas fa-exchange"></i> 切换</button>
      `)
    }
  ],
  server: {
    url: url + "/all",
    then: data => {
      deptData = data;
      return data.map(
        dept => [
          dept.id,
          dept.parentId,
          dept.name,
          dept.type,
          dept.principal,
          dept.phone,
          dept.remark
        ]
      );
    },
    total: data => data.totalElements,
    onError: res => res.text().then(txt => {
      console.error('部门数据获取错误:', txt);
      showToast('获取部门数据失败：' + txt, false);
    })
  },
  pagination: {
    limit: 5,
    server: {
      url: (prev, page, limit) => addQueryParam(prev, `size=${limit}&page=${page}`)
    }
  },
  search: false,
  sort: true,
  language: {
    pagination: {
      previous: '上一页',
      next: '下一页',
      showing: '显示第',
      of: '条，共',
      to: '至',
      results: '条记录'
    }
  }
};

// ============ 使用gridjs初始化表格 ============
function initGrid() {
  if (gridInstance) {
    gridInstance.destroy();
  }
  gridInstance = new gridjs.Grid(gridOptions).render(document.getElementById("gridjs-container"));
}

// ============ 页面加载初始化 ============
document.addEventListener('DOMContentLoaded', function() {
  initGrid();
});

// ============ 新增部门 ============
const addForm = document.getElementById('add-form');
if (addForm) {
  addForm.addEventListener('submit', (event) => {
    event.preventDefault();
    if (addForm.checkValidity()) {
      // 获取表单参数
      let jsonData = formJsonData(addForm);
      fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(jsonData)
      }).then(response => {
        if (response.ok) {
          // 获取模态框 DOM 元素，关闭模态框
          const deptModal = document.getElementById('addModal');
          bootstrap.Modal.getInstance(deptModal).hide();

          initGrid(); // 重新渲染表格

          showToast("成功添加新部门");
        } else {
          response.json().then(data => {
            showToast(data.message || '添加失败', false);
          });
        }
      }).catch(error => {
        console.error('Error:', error);
        showToast('添加部门失败', false);
      });
    } else {
      // 如果表单无效，添加was-validated类来显示Bootstrap验证样式
      addForm.classList.add('was-validated');
    }
  });
}

// ============ 编辑部门 ============
window.openEditModal = function(id) {
  // 从已加载的数据中查找部门信息
  let dept = deptData.find(item => item.id === id);
  if (dept) {
    const editForm = document.getElementById('edit-form');
    editForm.elements['id'].value = id;
    editForm.elements['parentId'].value = dept.parentId || '';
    editForm.elements['name'].value = dept.name || '';
    editForm.elements['type'].value = dept.type || '';
    editForm.elements['principal'].value = dept.principal || '';
    editForm.elements['phone'].value = dept.phone || '';
    editForm.elements['remark'].value = dept.remark || '';
    bootstrap.Modal.getOrCreateInstance(document.getElementById('editModal')).show();
  } else {
    // 如果内存中没有数据，从API获取
    fetch(`${url}/${id}`)
      .then(r => r.json())
      .then(data => {
        const editForm = document.getElementById('edit-form');
        // 修复：使用正确的字段名 'id' 而不是 'seq'
        ['id','parentId','name','type','principal','phone','remark']
          .forEach(k => editForm[k].value = data[k] ?? '');
        bootstrap.Modal.getOrCreateInstance(document.getElementById('editModal')).show();
      })
      .catch(error => {
        console.error('Error:', error);
        showToast('获取部门信息失败', false);
      });
  }
};

const editForm = document.getElementById('edit-form');
if (editForm) {
  // 修复：只绑定一次事件监听器，使用 PUT 方法
  editForm.addEventListener('submit', (event) => {
    event.preventDefault();
    if (editForm.checkValidity()) {
      // 获取表单参数
      let jsonData = formJsonData(editForm);
      fetch(url, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(jsonData)
      }).then(response => {
        if (response.ok) {
          // 获取模态框 DOM 元素，关闭模态框
          const deptModal = document.getElementById('editModal');
          bootstrap.Modal.getInstance(deptModal).hide();

          initGrid(); // 重新渲染表格

          showToast("编辑部门成功");
        } else {
          response.json().then(data => {
            showToast(data.message || '编辑失败', false);
          });
        }
      }).catch(error => {
        console.error('Error:', error);
        showToast('编辑部门失败', false);
      });
    } else {
      // 如果表单无效，添加was-validated类来显示Bootstrap验证样式
      editForm.classList.add('was-validated');
    }
  });
}

// ============ 启停部门 ============
window.toggleDept = function(id) {
  fetch(url + '/' + id + '/toggle', {method: 'PATCH'})
    .then(response => {
      if (response.ok) {
        initGrid();
        showToast('状态切换成功');
      } else {
        response.json().then(data => {
          showToast(data.message || '切换失败', false);
        });
      }
    })
    .catch(error => {
      console.error('Error:', error);
      showToast('切换失败', false);
    });
}

// ============ 表单数据转换成json格式 ============
function formJsonData(form) {
  const jsonData = {};
  const formData = new FormData(form);
  formData.forEach((value, key) => {
    if (!jsonData[key]) {
      jsonData[key] = formData.getAll(key).length > 1 ? formData.getAll(key) : formData.get(key);
    }
  });
  return jsonData;
}

// ============ 搜索功能 ============
const searchForm = document.getElementById('search-form');
if (searchForm) {
  searchForm.addEventListener('submit', (event) => {
    event.preventDefault();
    // 获取表单参数
    let formData = new FormData(searchForm);
    // 创建 URLSearchParams 对象
    let searchParams = new URLSearchParams(formData);
    // 获取查询字符串
    let params = searchParams.toString();
    // 将表单参数添加到url中
    gridOptions.server.url = addQueryParam(url, params);
    // 刷新表格
    gridInstance.updateConfig(gridOptions).forceRender();
  });

  // 重置搜索
  searchForm.addEventListener('reset', () => {
    gridOptions.server.url = url;
    gridInstance.updateConfig(gridOptions).forceRender();
  });
}